package jvm;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project Java_base
 * @create 2017-05-05 14:05
 * @desc VM args:-Xmx20M -XX:MaxDirectMemorySize=10M
 * 如果不指定DirectMemory，则默认与堆大小一致
 **/
public class DirectMemoryOOM {
    private static final int _1MB = 1024 * 1024;

    public static void main(String[] args) throws Exception {
        Field unsafeField = Unsafe.class.getDeclaredFields()[0];
        unsafeField.setAccessible(true);
        Unsafe unsafe = (Unsafe) unsafeField.get(null);
        while (true) {
            //分配DirectByteBuffer的方法是：
            //ByteBuffer.allocateDirect(int capacity)这样使用也会抛出内存溢出，
            //但它抛出异常的时并没有真正像操作系统申请分配内存，而是通过计算得知内存无法分配，手动抛出异常
            unsafe.allocateMemory(_1MB);//真正申请分配内存的方法
        }

    }
}
